package com.areaCalc;

import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CalculationList extends ListActivity {
	
	private Cursor model;
	private AreaCalcHelper helper;
	private AreaCalcAdapter adapter= null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_view);
		helper = new AreaCalcHelper(this);
		initList();
	
	}
	
	private void initList() {
		if (model!=null) {
			stopManagingCursor(model);
			model.close();
		}
		model=helper.getAll();
		startManagingCursor(model);
		adapter= new AreaCalcAdapter(model);
		setListAdapter(adapter);
	}
	
	class AreaCalcAdapter extends CursorAdapter {
		AreaCalcAdapter(Cursor c) {
			super(CalculationList.this, c);
		}
		
		@Override
		public void bindView(View row, Context context, Cursor cursor) {
			CalculationHolder holder = (CalculationHolder) row.getTag();
			holder.populateFrom(cursor,helper);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater=getLayoutInflater();
			View row=inflater.inflate(R.layout.row, parent, false);
			CalculationHolder holder=new CalculationHolder(row);
			row.setTag(holder);
			return(row);
		}
	}
	
	static class CalculationHolder {
		private TextView name=null;
		private TextView area=null;
		private ImageView icon=null;
		private View row=null;

		CalculationHolder(View row) {
			this.row=row;
			name=(TextView)row.findViewById(R.id.title);
			area=(TextView)row.findViewById(R.id.area);
			icon=(ImageView)row.findViewById(R.id.icon);
		}
		void populateFrom(Cursor c, AreaCalcHelper helper) {
			name.setText(helper.getName(c));
			area.setText(helper.getAddress(c));
			if (helper.getType(c).equals("sit_down")) {
//				icon.setImageResource(R.drawable.ball_red);
			}
			else if (helper.getType(c).equals("take_out")) {
//				icon.setImageResource(R.drawable.ball_yellow);
			}
			else {
//				icon.setImageResource(R.drawable.ball_green);
			}
		}
	}
}
